<?php

namespace app\api\service;

use app\common\model\User;
use app\common\model\UserAddress;
use app\Response;

class UserAddressService
{
    /**** 地址列表
     * @param $page int 页码
     * @param $num array 个数
     * @param $user_id int 用户ID
     * @return array
     */
    public static function getAddressList($page,$num,$user_id,$default){
        $where[] = ["enable","=",1];
        $where[] = ["uid","=",$user_id];
        if(!empty($default)){
            $where[] = ["default","=",$default];
        }
        $data = UserAddress::datalist($where,$page,$num);
        $count = UserAddress::listCount($where);
        return [$data,$count];
    }

    /**** 地址详情
     * @param $id int 地址ID
     * @param $user_id int 用户ID
     * @return array
     */
    public static function getAddressInfo($id,$user_id){
        $where[] = ["enable","=",1];
        $where[] = ["uid","=",$user_id];
        $where[] = ["id","=",$id];
        $info = UserAddress::addressInfo($where);
        return $info;
    }


    /**** 地址新增
     * @param $id int 地址ID
     * @param $user_id int 用户ID
     * @param $data array 地址信息数组
     * @return bool
     */
    public static function addressAddService($id,$user_id,$data){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        $data["u_type"] = $userInfo["type"];
        if(!empty($id)){
            if($data["default"] == 1){
                $where_one[] = ["uid","=",$user_id];
                $update_data["default"] = 0;
                UserAddress::addressEdit($where_one,["default"=>0]);
            }
            $where[] = ["id","=",$id];
            $res = UserAddress::addressEdit($where,$data);
        }else{
            if($data["default"] == 1){
                $where_one[] = ["uid","=",$user_id];
                $update_data["default"] = 0;
                UserAddress::addressEdit($where_one,["default"=>0]);
            }
            $res = UserAddress::addressInsert($data);
        }
        return $res;
    }

    /**** 地址删除
     * @param $id int 地址ID
     * @param $user_id int 用户ID
     * @return bool
     */
    public static function getAddressDel(int $id,int $user_id){
        $where[] = ["id","=",$id];
        $where[] = ["uid","=",$user_id];
        $data["enable"] = 0;
        return UserAddress::addressEdit($where,$data);
    }
}